﻿using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Paas.Pioneer.User.Application.Contracts.Login;
using Paas.Pioneer.User.Application.Contracts.Login.Dtos;
using Paas.Pioneer.User.Application.Contracts.User.Dtos;
using Senparc.Weixin;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using Volo.Abp;
using Volo.Abp.AspNetCore.Mvc;

namespace Paas.Pioneer.User.HttpApi.Controllers.OAuth2
{
    [Route("/api/user/[controller]")]
    public class OAuth2Controller : AbpController
    {
        private readonly ILoginService _service;

        public OAuth2Controller(ILoginService service)
        {
            _service = service;
        }

        //下面换成账号对应的信息，也可以放入web.config等地方方便配置和更换
        private readonly string _appId = Config.SenparcWeixinSetting.WeixinAppId; //与微信公众账号后台的AppId设置保持一致，区分大小写。
        private readonly string _appSecret = Config.SenparcWeixinSetting.WeixinAppSecret; //与微信公众账号后台的AppId设置保持一致，区分大小写。

        /// <summary>
        /// OAuthScope.snsapi_userinfo方式回调
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("callback-user")]
        public async Task<LoginOutput> UserInfoCallbackAsync([FromBody] UserInfoCallbackInput input)
        {
            if (string.IsNullOrEmpty(input.Code))
            {
                throw new BusinessException("您拒绝了授权！");
            }

            OAuthAccessTokenResult result = null;

            //通过，用code换取access_token
            try
            {
                result = await OAuthApi.GetAccessTokenAsync(_appId, _appSecret, input.Code);
            }
            catch (Exception ex)
            {
                throw new BusinessException(ex.Message);
            }

            if (result.errcode != ReturnCode.请求成功)
            {
                throw new BusinessException("错误：" + result.errmsg);
            }

            if (!string.IsNullOrEmpty(input.ReturnUrl))
            {
                throw new BusinessException($"returnUrl:{input.ReturnUrl}");
            }

            OAuthUserInfo userInfo = await OAuthApi.GetUserInfoAsync(result.access_token, result.openid);
            var userOutput = await _service.H5LoginAsync(userInfo, result.access_token, _appId);

            //下面2个数据也可以自己封装成一个类，储存在数据库中（建议结合缓存）
            //如果可以确保安全，可以将access_token存入用户的cookie中，每一个人的access_token是不一样的
            // HttpContext.Session.SetString("OAuthAccessTokenStartTime", SystemTime.Now.ToString());
            // HttpContext.Session.SetString("OAuthAccessToken", result.ToJson());
            return userOutput;
        }
    }
}